package com.sanjiahantang.youjiaclient.module.me.scheme.presenters;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;

import com.sanjiahantang.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseMvpPresenter;
import com.sanjiahantang.youjiaclient.base.CallBack;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.config.SPConfig;
import com.sanjiahantang.youjiaclient.module.common.beans.StringBean;
import com.sanjiahantang.youjiaclient.module.common.models.IUserModel;
import com.sanjiahantang.youjiaclient.module.common.models.impl.UserModel;
import com.sanjiahantang.youjiaclient.module.me.scheme.beans.MeCaseOBean;
import com.sanjiahantang.youjiaclient.module.me.scheme.models.IMeSchemeModel;
import com.sanjiahantang.youjiaclient.module.me.scheme.models.impl.MeSchemeModel;
import com.sanjiahantang.youjiaclient.module.me.scheme.views.MeSchemeView;
import com.sanjiahantang.youjiaclient.module.me.scheme.views.impl.MeSchemeDetailActivity;
import com.sanjiahantang.youjiaclient.module.programmeprice.views.impl.ProgramOrderActivity;
import com.sanjiahantang.youjiaclient.module.programmeprice.views.impl.ProgramPriceActivity;
import com.sanjiahantang.youjiaclient.utils.FileUtils;
import com.sanjiahantang.youjiaclient.utils.SPUtils;
import com.squareup.picasso.Picasso;

import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zy on 2017/9/8.
 */

public class MeSchemePresenter extends BaseMvpPresenter<MeSchemeView> {

    private IUserModel userModel;
    private MeSchemeView.OnLoadListener onLoadListener;
    private CommonNavigatorAdapter tabAdapter;

    private List<String> tabList;
    private List<List<MeCaseOBean.InformationListBean>> schemeList;
    private QuickAdapter<MeCaseOBean.InformationListBean> schemeAdapter;
    private IMeSchemeModel iMeSchemeModel;
    private QuickAdapter detailAdapter;
    private MeSchemeView.DetailCallBack detailCallBack;

    public MeSchemePresenter() {
        userModel = new UserModel();
        tabList = new ArrayList<>();
        schemeList = new ArrayList<>();
        iMeSchemeModel = new MeSchemeModel();
    }

    public void loadMySchemeList(Context context, final MeSchemeView.OnLoadListener onLoadListener) {
        mView.showProgress();
        Map<String, String> params = new HashMap<>();
        params.put(KEY_PHONE, "" + SPUtils.get(context, SPConfig.PHONE, ""));
        params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        userModel.loadSchemeList(context, params, new SchemeListCallBack());
        this.onLoadListener = onLoadListener;

        tabAdapter = new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return tabList.size();
            }

            @Override
            public IPagerTitleView getTitleView(final Context context, final int index) {
                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(context);
                View contentView = LayoutInflater.from(context).inflate(R.layout.item_radio_line, null);
                commonPagerTitleView.setContentView(contentView);
                final RadioButton btn = (RadioButton) contentView.findViewById(R.id.rbItem);
                btn.setText(tabList.get(index));

                commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {
                    @Override
                    public void onSelected(int i, int i1) {
                        btn.setChecked(true);
                    }

                    @Override
                    public void onDeselected(int i, int i1) {
                        btn.setChecked(false);
                    }

                    @Override
                    public void onLeave(int i, int i1, float v, boolean b) {

                    }

                    @Override
                    public void onEnter(int i, int i1, float v, boolean b) {

                    }
                });
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onLoadListener.switchPages(index);
                        reloadData(context, index);
                    }


                });
                commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onLoadListener.switchPages(index);
                        reloadData(context, index);
                    }
                });
                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                return null;
            }
        };
        onLoadListener.initTabs(tabAdapter);

        schemeAdapter = new QuickAdapter<MeCaseOBean.InformationListBean>(context, R.layout.item_case_list) {
            @Override
            protected void convert(BaseAdapterHelper helper, final MeCaseOBean.InformationListBean item) {
                helper.getView(R.id.llCollect).setVisibility(View.GONE);
                // helper.setText(R.id.tv_case_detail, item.getInformationList().get(0).getLikeStyleName() + " ， " + item.getLikeStyleCode());
                ImageView ivCaseMain = helper.getView(R.id.ivCaseMain);
                Picasso.with(context).load(FileUtils.rePath(item.getUrl()))
                        .placeholder(R.drawable.i_match)
                        .into(ivCaseMain);



                helper.setVisible(R.id.llCollect, false);
                helper.setVisible(R.id.txtCaseTitle, false);
                helper.setText(R.id.tv_case_detail, item.getLikeStyleName() + "," + item.getApartmentTypeName());
                helper.setOnClickListener(R.id.ivCaseMain, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, MeSchemeDetailActivity.class);
                        intent.putExtra(KEY_ID, String.valueOf(item.getPpId()));
                        intent.putExtra(KEY_VERSION,item.getUrl());
                        context.startActivity(intent);
                    }
                });
            }
        };
        onLoadListener.initList(schemeAdapter);
    }

    public void setDetailCallBack(MeSchemeView.DetailCallBack detailCallBack) {
        this.detailCallBack = detailCallBack;
    }

    private void reloadData(Context context, int id) {
        schemeAdapter.clear();
        schemeAdapter.addAll(schemeList.get(id));

    }

    //载入明细方案明细
    public void loadCaseById(Context context, String id) {
        Map<String, String> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put(KEY_ID, id);
        mView.showProgress();
        iMeSchemeModel.loadMeCaseById(context, param, new CallBack<MeCaseOBean> (){

            @Override
            public void onSuccess(MeCaseOBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (detailAdapter == null) {
                    detailAdapter = new QuickAdapter<MeCaseOBean.PicList>(context, R.layout.item_case_info) {
                        @Override
                        protected void convert(BaseAdapterHelper helper, MeCaseOBean.PicList item) {

                            ImageView ivIcon = helper.getView(R.id.ivIcon);
                            helper.setText(R.id.txtName, item.getPicCaName());
                            ivIcon.setImageResource(MeSchemeView.IMAGE_RES_IDS[item.getPicCaId()]);
                            ImageView ivPhoto = helper.getView(R.id.ivPhoto);
                            Picasso.with(context).load(FileUtils.rePath(item.getUrl()))
                                    .placeholder(R.drawable.i_match)
                                    .into(ivPhoto);
                        }
                    };
                    detailCallBack.initAdapter(detailAdapter);
                }
                List<MeCaseOBean.PicList> picList = new ArrayList<>();
                if (response != null && response.getData() != null && response.getData().getPicList() != null){
                    for (int i = 0; i < response.getData().getPicList().size(); i++) {
                        if (15 != response.getData().getPicList().get(i).getPicCaId()) {
                            picList.add(response.getData().getPicList().get(i));
                        } else {
                            ConfigValue.data = response.getData().getPicList().get(i);
                        }
                    }
                }

                detailAdapter.clear();
                detailAdapter.addAll(picList);

                if (response != null && response.getData() != null && response.getData().getInformationList() != null && response.getData().getInformationList().size() > 0){
                    detailCallBack.loadData(response.getData());

                    detailCallBack.loadVersion(response.getData().getInformationList().get(0).getVersion());
                }else{
                    Utils.showToast(context,"找不到该方案");
                    ((Activity)context).finish();
                    return;
                }


            }

            @Override
            public void onFailure(String message) {

                mView.hideProgress();
            }
        });
    }

    //报价清单检查是否下单 如果下单跳转支付页面  否则跳转报价清单页面
    public void checkISPlanceOrder(Context context, final String ppId, final String version) {
        Map<String, String> map = new HashMap<>();
        map.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        map.put("planId",ppId);
        iMeSchemeModel.loadCheckOrder(context, map, new CallBack<StringBean>() {
            @Override
            public void onSuccess(StringBean response, Context context, Object tag) {
                if (mView==null){
                    return;
                }
                if (response != null && response.getCode() == RESPONSE_CODE_SUC){
                    if (TextUtils.equals("true",response.getData())){
                        context.startActivity(new Intent(context, ProgramOrderActivity.class)
                                .putExtra(KEY_ID,Integer.valueOf(ppId))
                        );
                    }else{
                        context.startActivity(new Intent(context, ProgramPriceActivity.class)
                            .putExtra(KEY_ID,ppId).putExtra(KEY_VERSION,version).putExtra(KEY_TYPE,0)
                        );
                    }
                }
            }

            @Override
            public void onFailure(String message) {

            }
        });
    }


    private class SchemeListCallBack implements CallBack<MeCaseOBean.InfoListData> {

        @Override
        public void onSuccess(MeCaseOBean.InfoListData response, Context context, Object tag) {
            if (mView == null) return;
            mView.hideProgress();
            if (response == null || response.getNameList() == null) return;
            tabList.clear();
            tabList.addAll(response.getNameList());
            tabAdapter.notifyDataSetChanged();
            schemeList.clear();
            schemeList.addAll(response.getList());


            if (schemeList.size() > 0) {
                schemeAdapter.addAll(schemeList.get(0));
                reloadData(context, 0);
            }
        }

        @Override
        public void onFailure(String message) {
            if (mView == null) return;
            mView.hideProgress();
        }
    }
}
